<?php

namespace cms\modules\v1\models\access;

use cms\modules\v1\models\admin\Admin;
use cms\modules\v1\models\admin\AdminRole;
use cms\modules\v1\models\Common;
use common\models\Functions;
use common\models\Status;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "project_info".
 *
 * @property int    $id
 * @property string $name
 */
class Module extends Common
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%module}}';
    }

    public function getTree()
    {
        try {
            #获取第一级
            $moduleList = static::getListMapByCache();
            ArrayHelper::multisort($moduleList, 'list_order', SORT_ASC);
            $top = $this->getSubLevel($moduleList, 0);
            $result = [];
            foreach ($top as $v) {
                $tmp = $v;
                $subLevel = $this->getSubLevel($moduleList, $v['id']);

                if (!empty($subLevel)) {
                    foreach ($subLevel as $kk => $vv) {
                        $sSubLevel = $this->getSubLevel($moduleList, $vv['id']);
                        if (!empty($sSubLevel)) {
                            $subLevel[$kk]['children'] = $sSubLevel;
                        }
                    }
                    $tmp['children'] = $subLevel;

                }
                $result[] = $tmp;
            }
            return Functions::formatRestAPI(0, '', $result);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 获取选择框树形结构
     * @return array
     */
    public function getTreeMap()
    {
        try {
            #获取第一级
            $moduleList = static::getListMapByCache();
            $top = $this->getSubLevel($moduleList, 0);
            $result = [];
            foreach ($top as $v) {
                $result[] = [
                    'id' => $v['id'],
                    'name' => $v['meta_title'],
                ];
                $subLevel = $this->getSubLevel($moduleList, $v['id']);
                if (!empty($subLevel)) {
                    foreach ($subLevel as $kk => $vv) {
                        $result[] = [
                            "id" => $vv['id'],
                            "name" => "|------" . $vv['meta_title']
                        ];
                        $sSubLevel = $this->getSubLevel($moduleList, $vv['id']);
                        if (!empty($sSubLevel)) {
                            foreach ($subLevel as $vvv) {
                                $result[] = [
                                    "id" => $vvv['id'],
                                    "name" =>  "|------------" . $vvv['meta_title']
                                ];
                            }
                        }
                    }
                    $tmp['children'] = $subLevel;

                }
            }

            return Functions::formatRestAPI(0, '', $result);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function saveInfo() {
        try {
            /*
             * id, path, name, component, parent_id, meta_title,
               meta_hide_in_bread, meta_hide_in_menu, meta_no_cache, list_order,
               status
             * */
            $post = \Yii::$app->request->post();
            $id = (int) $post['id'];

            if (empty($post['path'])) {
                throw new Exception("路径不能为空");
            }
            $data['path'] = $post['path'];

            if (empty($post['name'])) {
                throw new Exception("路径名称不能为空");
            }
            $data['name'] = $post['name'];

            if (empty($post['component'])) {
                throw new Exception("组件不能为空");
            }
            $data['component'] = $post['component'];

            if (empty($post['meta_title'])) {
                throw new Exception("菜单名称不能为空");
            }
            $data['meta_title'] = $post['meta_title'];
            $data['meta_icon'] = $post['meta_icon'];
            $data['meta_hide_in_bread'] = (int) $post['meta_hide_in_bread'];
            $data['meta_hide_in_menu'] = (int) $post['meta_hide_in_menu'];
            $data['meta_no_cache'] = (int) $post['meta_no_cache'];
            $data['list_order'] = (int) $post['list_order'];
            $data['status'] = (int) $post['status'];

            $data['parent_id'] = empty($post['parent_id']) ? 0 : $post['parent_id'];
            if ($data['parent_id'] == 0) {
                $data['level_path'] = "0,";
            } else {
                $parentInfo = static::getOneInfoById($data['parent_id']);
                $data['level_path'] = $parentInfo['level_path'] . $data['parent_id'] . ",";
            }
            if (empty($id)) {
                $res = static::insertData($data);
                if ($res == false) {
                    throw new Exception("系统错误");
                }
            } else {
                $res = static::updateData($data, ["id" => $id]);
                if ($res === false) {
                    throw new Exception("系统错误");
                }
            }

            return Functions::formatRestAPI(0, "编辑成功");
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 接口获取菜单信息
     * @return array
     */
    public function getModules()
    {
        try {
            $adminInfo = (new Admin())->checkLogin();
            $where['id'] = $adminInfo['role_type'];

//            if ($adminInfo['role_type'] != 1) {
//                $where['is_super'] = Status::COMMON_RADIO_NO;
//            }

            $roleInfo = AdminRole::getOneByWhere($where, ['role_permissions']);

            $modules = $this->getModuleList($roleInfo['role_permissions']);

            $top = $this->getSubLevel($modules, 0);

            $recursion = $this->module($modules, $top);

            return Functions::formatRestAPI(0, '', $recursion);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 切换状态
     * @return array
     */
    public function saveOrder() {
        try {

            $post = \Yii::$app->request->post();

            $id = $post['id'];
            if (empty($id)) {
                throw new Exception('未知信息');
            }

            $data['list_order'] = (int) $post['order'];
            $res = static::updateData($data, ['id' => $id]);
            if ($res === false) {
                throw new Exception('系统错误，请联系开发小哥哥');
            }
            return Functions::formatRestAPI(0, '切换成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getInfo($id = 0) {
        try {
            if (empty($id)) {
                throw new Exception('未知信息');
            }

            $info = static::getOneInfoById($id);
            if (empty($info)) {
                throw new Exception('未知模块信息');
            }

            $info['parent_id'] = (int) $info['parent_id'];

            return Functions::formatRestAPI(0, '', $info);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 根据列表获取下一级
     * @param array $moduleList
     * @param int   $parent
     *
     * @return array
     */
    public function getSubLevel($moduleList = [], $parent = 0)
    {
        $result = [];
        foreach ($moduleList as $v) {
            if ($v['parent_id'] == $parent) {
                $result[] = $v;
            }
        }

        return $result;
    }


    /**
     * 对数组进行组装
     *
     * @param array $moduleList
     *
     * @return array
     */
    public function module($moduleList = [], $top = [])
    {
        $result = [];
        foreach ($top as $v) {
            $tmp = static::formatData($v);
            $children = $this->recursionModule($moduleList, $v['id']);
            if (!empty($children)) {
                $tmp['children'] = $children;
            }
            $result[] = $tmp;
        }

        return $result;
    }

    /**
     * 递归获取子元素
     *
     * @param     $moduleList
     * @param int $parentId
     *
     * @return array|mixed
     */
    private function recursionModule($moduleList, $parentId = 0)
    {

        $return = $this->moduleChild($moduleList, $parentId);

        if (!empty($return)) {
            foreach ($return as $k => $v) {
                $children = $this->moduleChild($moduleList, $v['id']);
                if (empty($children)) {
                    break;
                }
                $return[ $k ]['children'] = $this->recursionModule($moduleList, $v['id']);
            }
        }

        return $return;
    }

    /**
     * 获取总列表
     */
    public function getModuleList($permissions = '')
    {
        if (!empty($permissions) && $permissions != -1) {
            $roleArr = explode(",", $permissions);
            $where['id'] = $roleArr;
        }
        $where['status'] = Status::COMMON_RADIO_YES;

        return $this->getByWhere($where, '*', 'list_order ASC');
    }

    /**
     * 获取子元素
     *
     * @param $moduleInfo
     * @param $parentId
     *
     * @return array
     */
    public function moduleChild($moduleInfo, $parentId)
    {
        $return = [];
        foreach ($moduleInfo as $k => $v) {
            if ($v['parent_id'] == $parentId) {
                $return[] = static::formatData($v);
            }
        }

        return $return;
    }

    public static function formatData($oneData = [])
    {
        if (empty($oneData)) {
            return [];
        }

        $data = [
            'id' => $oneData['id'],
            'path' => $oneData['path'],
            'name' => $oneData['name'],
            'component' => $oneData['component'],
            'meta' => [
                'title' => $oneData['meta_title'],
                'icon' => $oneData['meta_icon'],
                'hideInBread' => $oneData['meta_hide_in_bread'] == Status::COMMON_RADIO_YES,
                'hideInMenu' => $oneData['meta_hide_in_menu'] == Status::COMMON_RADIO_YES,
                'noCache' => $oneData['meta_no_cache'] == Status::COMMON_RADIO_YES,
            ],
        ];

        return $data;
    }

}
